package com.seata.demo.order.config;


import io.seata.core.context.RootContext;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Seata过滤器，用于在HTTP请求间传递xid
 */
@Component
public class SeataFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 从请求头中获取xid并设置到RootContext
        String xid = req.getHeader(RootContext.KEY_XID);
        boolean isBind = false;

        if (xid != null) {
            RootContext.bind(xid);
            isBind = true;
        }

        try {
            chain.doFilter(req, res);
        } finally {
            // 清理上下文
            if (isBind) {
                RootContext.unbind();
            }
        }
    }
}

